from utils.db import db


class Member:
    def __init__(self):
        self.id = None
        self.name = ""
        self.phone = ""
        self.gender = ""
        self.birth_date = None
        self.membership_level = "普通会员"
        self.points = 0
        self.total_consumption = 0.0

    @staticmethod
    def get_all():
        """获取所有会员"""
        sql = "SELECT * FROM members ORDER BY created_at DESC"
        return db.fetch_all(sql)

    @staticmethod
    def get_by_id(member_id):
        """根据ID获取会员"""
        sql = "SELECT * FROM members WHERE id = ?"
        return db.fetch_one(sql, (member_id,))

    @staticmethod
    def get_by_phone(phone):
        """根据手机号获取会员"""
        sql = "SELECT * FROM members WHERE phone = ?"
        return db.fetch_one(sql, (phone,))

    def save(self):
        """保存或更新会员信息"""
        if self.id:
            sql = """
            UPDATE members 
            SET name=?, phone=?, gender=?, birth_date=?, 
                membership_level=?, points=?, total_consumption=?
            WHERE id=?
            """
            params = (self.name, self.phone, self.gender, self.birth_date,
                      self.membership_level, self.points, self.total_consumption, self.id)
        else:
            sql = """
            INSERT INTO members (name, phone, gender, birth_date, 
                               membership_level, points, total_consumption)
            VALUES (?, ?, ?, ?, ?, ?, ?)
            """
            params = (self.name, self.phone, self.gender, self.birth_date,
                      self.membership_level, self.points, self.total_consumption)

        db.execute(sql, params)
        return True

    @staticmethod
    def delete(member_id):
        """删除会员"""
        sql = "DELETE FROM members WHERE id = ?"
        db.execute(sql, (member_id,))
        return True
